#!/bin/bash

# 主服务器的IP地址
IP_MASTER="192.168.21.224"
# 集群的IP前缀
IP_CLUSTER="192.168.21"
# 需要远程访问的IP前缀
IP_REMOTES=(
  "192.168.10"
  "192.168.11"
  "192.168.20"
  "192.168.21"
)
# 复制数据库用户repl的密码
REPL_PASS="Ceeety123!@#"

echo "安装RPM包..."
rpm -ivh *.rpm
echo "---done"
sleep 1

echo "创建数据库目录并初始化数据..."
mkdir -p /opt/pgsql/12/data/
mkdir -p /opt/pgsql/12/log/
mkdir -p /opt/pgsql/12/pg_archive/
chown -R postgres:postgres /opt/pgsql/
sleep 1


echo "处理系统服务启动参数..."
sed -i 's/\/var\/lib\/pgsql\/12\/data\//\/opt\/pgsql\/12\/data\//g' /usr/lib/systemd/system/postgresql-12.service
systemctl daemon-reload
sleep 1

# echo "启动服务..."
# systemctl enable postgresql-12 && systemctl start postgresql-12
# echo "---done"
# sleep 1

echo "从主服务器导入数据..."
pg_basebackup -h $IP_MASTER -U repl -D /opt/pgsql/12/data/ -X stream -P
sleep 1

echo "配置为辅服务器"
echo standby='on' > /opt/pgsql/12/data/standby.signal

echo "配置启动参数: 6G mem, 4 cores, HDD"
cat>/opt/pgsql/12/data/postgresql.conf<<EOF
max_connections = 200
shared_buffers = 1536MB
effective_cache_size = 4608MB
maintenance_work_mem = 384MB
checkpoint_completion_target = 0.9
wal_buffers = 16MB
default_statistics_target = 100
random_page_cost = 4
effective_io_concurrency = 2
work_mem = 3932kB
min_wal_size = 1GB
max_wal_size = 4GB
max_worker_processes = 4
max_parallel_workers_per_gather = 2
max_parallel_workers = 4
max_parallel_maintenance_workers = 2
log_directory = '/opt/pgsql/12/log'    # directory where log files are written,
## below is for recovery settings
recovery_target_timeline = 'latest'   #同步到最新数据
primary_conninfo = 'host=$IP_MASTER port=5432 user=repl password=$REPL_PASS'   #连接到主库信息
EOF

chown -R postgres:postgres /opt/pgsql/
chmod -R 700 /opt/pgsql/

echo "配置IP访问权限"
cat>/opt/pgsql/12/data/pg_hba.conf<<EOF
local   all             all                                     peer
host    all             all             127.0.0.1/32            ident
host    replication     repl            $IP_CLUSTER.0/24         md5
host    all             repl            $IP_CLUSTER.0/24         trust
EOF
for (( i=0;i<${#IP_REMOTES[@]};i++ )) do
echo "host    all             dbuser          ${IP_REMOTES[i]}.0/24         md5">>/opt/pgsql/12/data/pg_hba.conf
done;
echo "重启服务"
systemctl restart postgresql-12
echo "---done"
sleep 1
